#include "mkEqu.h"


vector* mkVector(int len) {
  vector *v = (vector*)malloc(sizeof(vector));
  int k;

  v->eles = (double*)malloc(sizeof(double) * len);
  v->len = len;
  for (k=0;k<len;k++)
    v->eles[k] = 0;

  return v;
}

void freeVector(vector *v) {
  int i;

  free(v->eles);
  free(v);
}

matrix* mkMatrix(int r, int c) {
  matrix *m = (matrix*)malloc(sizeof(matrix));
  int i, j;

  m->height = r;
  m->width = c;
  m->rows = malloc(sizeof(vector) * r);
  for (i=0;i<r;i++) {
    m->rows[i].eles = malloc(sizeof(double) * c);
    m->rows[i].len = c;
    for (j=0;j<c;j++)
      m->rows[i].eles[j] = 0;
  }
  
  return m;
}

void freeMatrix(matrix *m) {
  int i;

  for (i=0;i<m->height;i++)
    free(m->rows[i].eles);
  free(m->rows);
  free(m);
}


equation* mkEquation(int in, int out, matrix *pnts) {
  equation *e = malloc(sizeof(equation));
  e->input = mkVector(in);
  e->coeff = mkMatrix(pnts->height, out);
  int i, j, k;

  e->in = in;
  e->out = out;
  
  for (i=0;pnts->height > pnts->width - out;) {
    incVector(pnts->rows+i, pnts->rows + pnts->height - 1);
    pnts->height--;

    if (i == pnts->width - out)
      i = 0;
    else
      i++;
  } 
  
  rowEschelon(pnts);
  for (int i=0;i<pnts->height;i++)
    for (int j=0;j<out;j++)
      setMElement(e->coeff, i, j,
		  getMElement(pnts, i, j + pnts->height + 1));
  
  return e;
}


vector* setVElement(vector *v, int e, double val) {
  v->eles[e] = val;
  return v;
}

matrix* setMElement(matrix *m, int r, int c, double val) {
  setVElement( m->rows + r, c, val);
}

double getMElement(matrix *m, int r, int c) {
  return getVElement(m->rows + r, c);
}

double getVElement(vector *v, int e) {
  return v->eles[e];
}


matrix* transpose(matrix *m) {
  matrix *t = mkMatrix(m->width, m->height);
  int x, y;
  
  for (x=0;x<m->width;x++) {
    for (y=0;y<m->height;y++) {
      setMElement(t, x, y, getMElement(m, y, x));
    }
  }

  return t;
}
